package cn.heycm.blog.console.infra.dao.article;

import cn.heycm.blog.console.domain.article.repository.AdminArticleRepository;
import cn.heycm.blog.console.infra.convert.ArticleConverter;
import cn.heycm.blog.console.infra.dao.article.entity.Article;
import cn.heycm.blog.console.infra.dao.article.entity.ArticleHistory;
import cn.heycm.blog.console.infra.dao.article.mapper.AdminArticleMapper;
import cn.heycm.blog.console.infra.dao.article.mapper.ArticleHistoryMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文章存储实现
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/18 21:19
 */
@Repository
@AllArgsConstructor
public class AdminArticleRepositoryImpl implements AdminArticleRepository {

    private final AdminArticleMapper adminArticleMapper;
    private final ArticleHistoryMapper articleHistoryMapper;

    @Override
    public Article findById(long articleId) {
        return adminArticleMapper.selectByPrimaryKey(articleId);
    }

    @Override
    @Transactional
    public void save(Article article) {
        if (null != article.getArticleId()) {
            adminArticleMapper.updateByPrimaryKeySelective(article);
        } else {
            adminArticleMapper.insertSelective(article);
        }
        ArticleHistory history = ArticleConverter.INST.toHistory(article);
        articleHistoryMapper.insertSelective(history);
    }

    @Override
    public List<ArticleHistory> findHistory(long articleId) {
        return articleHistoryMapper.selectByArticleId(articleId);
    }
}
